package com.tongtech.system.controller;

import com.tongtech.common.core.constant.UserConstants;
import com.tongtech.common.core.utils.StringUtils;
import com.tongtech.common.core.web.controller.BaseController;
import com.tongtech.common.core.web.domain.AjaxResult;
import com.tongtech.common.log.annotation.Log;
import com.tongtech.common.log.enums.BusinessType;
import com.tongtech.common.security.annotation.RequiresPermissions;
import com.tongtech.common.security.utils.SecurityUtils;
import com.tongtech.system.domain.Product;
import com.tongtech.system.service.IProductService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品信息
 *
 * @author xingyc
 */
@RestController
@RequestMapping("/product")
public class ProductController extends BaseController
{
    @Autowired
    private IProductService productService;

    /**
     * 获取产品列表
     */
    @RequiresPermissions("basicdata:product:list")
    @GetMapping("/list")
    public AjaxResult list(Product product)
    {
        List<Product> products = productService.selectProductList(product);
        return success(products);
    }

    /**
     * 查询产品列表（排除节点）
     */
    @RequiresPermissions("basicdata:product:list")
    @GetMapping("/list/exclude/{productId}")
    public AjaxResult excludeChild(@PathVariable(value = "productId", required = false) Long productId)
    {
        List<Product> products = productService.selectProductList(new Product());
        products.removeIf(p -> p.getProductId().intValue() == productId || ArrayUtils.contains(StringUtils.split(p.getAncestors(), ","), productId + ""));
        return success(products);
    }

    /**
     * 根据产品编号获取详细信息
     */
    @RequiresPermissions("basicdata:product:query")
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable Long productId)
    {
        return success(productService.selectProductById(productId));
    }

    /**
     * 新增产品
     */
    @RequiresPermissions("basicdata:product:add")
    @Log(title = "产品管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Product product)
    {
        if (!productService.checkProductNameUnique(product))
        {
            return error("新增产品'" + product.getProductName() + "'失败，产品名称已存在");
        }
        product.setCreateBy(SecurityUtils.getUsername());
        return toAjax(productService.insertProduct(product));
    }

    /**
     * 修改产品
     */
    @RequiresPermissions("basicdata:product:edit")
    @Log(title = "产品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Product dept)
    {
        Long deptId = dept.getProductId();
        if (!productService.checkProductNameUnique(dept))
        {
            return error("修改产品'" + dept.getProductName() + "'失败，产品名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改产品'" + dept.getProductName() + "'失败，上级产品不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && productService.selectNormalChildrenProductById(deptId) > 0)
        {
            return error("该产品包含未停用的子产品！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(productService.updateProduct(dept));
    }

    /**
     * 删除产品
     */
    @RequiresPermissions("basicdata:product:remove")
    @Log(title = "产品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (productService.hasChildByProductId(deptId))
        {
            return warn("存在下级产品,不允许删除");
        }
        return toAjax(productService.deleteProductById(deptId));
    }

    /**
     * 获取产品列表
     */
    @RequiresPermissions("basicdata:product:list")
    @GetMapping("/productTree")
    public AjaxResult industryTree(Product product)
    {
        return success(productService.selectProductTreeList(product));
    }
}
